package com.example.miscontactos;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import BaseDeDatos.AccesoABaseDeDatos;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.miscontactos.Entidades.Contacto;
import com.example.miscontactos.Entidades.HistorialClass;

public class Historial extends ListActivity 
{
	private SharedPreferences preferenciaOrden;
	private SharedPreferences preferenciaFiltro;
	private int accionIdPosition;
	Map<Integer,Integer> map = new HashMap<Integer, Integer>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_historial);
		
		cargarDatos();
	}
	
	private void cargarDatos()
	{
		String orden = getOrden();
		Boolean filtroAMostrar[] = getFiltros();
		
		Cursor cur = null;
		if (filtroAMostrar[0] && filtroAMostrar[1] && filtroAMostrar[2] && filtroAMostrar[3])
		{
			cur	= AccesoABaseDeDatos.obtenerHistorialCompleto(this, orden);
		}
		else
		{
			cur = AccesoABaseDeDatos.obtenerHistorialFiltrado(this, orden, filtroAMostrar);
		}
		
		if (cur.getCount() > 0)
		{
			HistorialClass[] historial_data = cargarDatos(cur);
			
	        HistorialAdapter adapter = new HistorialAdapter(this, 
	                R.layout.fila_historial, historial_data);
	                
	        setListAdapter(adapter);
	        registerForContextMenu(getListView());
		}
        else
        {
        	String[] values = new String[] { getResources().getString (R.string.historial_sin_acciones) };
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
					  android.R.layout.simple_list_item_1, android.R.id.text1, values);
			setListAdapter(adapter);
        }
	}
	
	@Override
	protected void onResume() 
	{
	    super.onResume();
	    cargarDatos();
	}
	
	private String getOrden()
	{
		String orden = "";
		preferenciaOrden = PreferenceManager.getDefaultSharedPreferences(this);
		Boolean asc = preferenciaOrden.getBoolean("orden_historial", false);
		
		if (asc)
		{
			orden = "DESC";
		}
		else 
		{
			orden = "ASC";
		}
		
		return orden;
	}
	
	private Boolean[] getFiltros()
	{
		Boolean filtros[] = new Boolean[4];
		
		preferenciaFiltro = PreferenceManager.getDefaultSharedPreferences(this);
		Boolean mostrar = preferenciaFiltro.getBoolean("mostrar_mensajes", true);
		filtros[0] = mostrar;
		mostrar = preferenciaFiltro.getBoolean("mostrar_llamadas", true);
		filtros[1] = mostrar;
		mostrar = preferenciaFiltro.getBoolean("mostrar_mails", true);
		filtros[2] = mostrar;
		mostrar = preferenciaFiltro.getBoolean("mostrar_mensajes_web", true);
		filtros[3] = mostrar;
		
		return filtros;		
	}
	
	public HistorialClass[] cargarDatos(Cursor cur)
	{
		HistorialClass historial_data_array[] = new HistorialClass[cur.getCount()];
		ArrayList<HistorialClass> historial_data = new ArrayList<HistorialClass>();
		
		cur.moveToFirst();
		
		do
	    {
			HistorialClass item = new HistorialClass();
			item.id = cur.getInt(0);
			item.contacto = cur.getString(4);
			item.tipoAccion = cur.getInt(5);
			item.fecha = cur.getString(6);
			historial_data.add(item);
		}while (cur.moveToNext());
		
		historial_data_array = new HistorialClass[historial_data.size()];
		historial_data_array = historial_data.toArray(historial_data_array);
		
		return historial_data_array;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		menu.add(Menu.NONE, 0, 0, getResources().getString (R.string.menu_preferencias));
    	return super.onCreateOptionsMenu(menu);
	}
	
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) 
    {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		menu.clear();
		menu.setHeaderTitle(getResources().getString(R.string.titulo_menu_contextual));
		menu.addSubMenu(getResources().getString(R.string.sub_menu_borrar_accion));
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
		accionIdPosition = info.position;
		inflater.inflate(R.menu.contact_menu, menu);
	}
	
	@Override
    public boolean onContextItemSelected(MenuItem item) 
    {
		int id = map.get(accionIdPosition);
    	AccesoABaseDeDatos.borrarAccionHistorial(this, id);
    	
    	return true;
    }
	
	 @Override
    public boolean onOptionsItemSelected(MenuItem item) 
     {
     	 switch (item.getItemId()) 
    	 {
    		 case 0:
    			 Intent intent = new Intent(Historial.this, Preferencias.class);
    	    	 startActivity(intent);
                 return true;
         }
         return false;
	}
	
	public class HistorialAdapter extends ArrayAdapter<HistorialClass>{

        Context context; 
        int layoutResourceId;    
        HistorialClass data[] = null;
        
        public HistorialAdapter(Context context, int layoutResourceId, HistorialClass[] data) {
            super(context, layoutResourceId, data);
            this.layoutResourceId = layoutResourceId;
            this.context = context;
            this.data = data;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) 
        {
            View row = convertView;
            HistorialHolder holder = null;
            final HistorialClass historialRow = data[position];
            
            if(row == null)
            {
                LayoutInflater inflater = ((Activity)context).getLayoutInflater();
                row = inflater.inflate(layoutResourceId, parent, false);
                
                holder = new HistorialHolder();
                holder.imgAccion = (ImageView)row.findViewById(R.id.imagenAccion);
                holder.txtContacto = (TextView)row.findViewById(R.id.txtNombreContacto);
                holder.txtFecha = (TextView)row.findViewById(R.id.txtFecha);
                                                
                row.setTag(holder);
            }
            else
            {
                holder = (HistorialHolder)row.getTag();
            }
            
            ContentResolver cr = getContentResolver();
            Contacto contactoSeleccionado;
            contactoSeleccionado = Contacto.GetContacto(cr, String.valueOf(historialRow.contacto));
            
            holder.txtContacto = SetearLayoutNombre(holder.txtContacto, contactoSeleccionado.displayName);
            holder.txtFecha = SetearLayoutFecha(holder.txtFecha, historialRow.fecha);
            holder.imgAccion = SetearLayoutImagen(holder.imgAccion);
            map.put(position, historialRow.id);
            
            switch (historialRow.tipoAccion) 
       	 	{
       	 		case 1:
       	 			holder.imgAccion.setImageResource(R.drawable.sms);
       	 			break;
       	 		case 2:
       	 			holder.imgAccion.setImageResource(R.drawable.tel2);
       	 			break;
       	 		case 3:
       	 			holder.imgAccion.setImageResource(R.drawable.mail);
       	 			break;
       	 		case 4:
       	 			break;
            }
            
            return row;
        }
        
        private TextView SetearLayoutNombre(TextView txtView, String texto)
        {
        	LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)txtView.getLayoutParams();
        	params.setMargins(20, 10, 0, 0);
        	txtView.setLayoutParams(params);
        	txtView.setText(texto);
        	return txtView;
        }
        
        private TextView SetearLayoutFecha(TextView txtView, String texto)
        {
        	LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)txtView.getLayoutParams();
        	params.setMargins(20, 0, 0, 0);
        	txtView.setLayoutParams(params);
        	txtView.setText(texto);
        	return txtView;
        }
        
        private ImageView SetearLayoutImagen(ImageView imgAccion)
        {
        	LinearLayout.LayoutParams params = 
                    new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
                                    LayoutParams.WRAP_CONTENT);
        	params.setMargins(15, 0, 0, 0);
        	imgAccion.setLayoutParams(params);
            imgAccion.getLayoutParams().height = 70;
            imgAccion.getLayoutParams().width  = 55;
            return imgAccion;
        }
        
        public class HistorialHolder
        {
            TextView txtContacto;
            TextView txtFecha;
            ImageView imgAccion;
        }
    }

}
